package logic

import (
	"context"
	"errors"
	"fmt"
	"order_srv/models/mysql"
	"time"

	"order_srv/internal/svc"
	"order_srv/order_srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *order_srv.CreateOrderRequest) (*order_srv.CreateOrderResponse, error) {
	// todo: add your logic here and delete this line

	order := mysql.Order{
		UserId:    int(in.UserId),
		OrderSn:   in.OrderSn,
		Payment:   in.Payment,
		VipPrice:  float64(in.VipPrice),
		Price:     float64(in.Amount),
		Num:       int(in.Num),
		PayTime:   time.Now().String(),
		PayStatus: 1,
	}

	fmt.Println(order)

	err := order.CreateOrder()

	if err != nil {
		return nil, errors.New("订单创建失败")
	}

	orderGoods := mysql.OrderGoods{
		OrderSn: in.OrderSn,
		Title:   "鲇鱼讲go",
		Cover:   "测试封面",
		Price:   float64(in.Price),
	}

	err = orderGoods.CreateOrderGoods()

	if err != nil {
		err = order.DeleteOrder(in.OrderSn) //若是订单商品信息没有储存成功的话将刚刚添加的订单信息进行删除避免垃圾数据
		if err != nil {
			return nil, errors.New("订单创建失败")
		}
		return nil, errors.New("订单创建失败")
	}

	return &order_srv.CreateOrderResponse{
		Title:   "鲇鱼讲go",
		OrderSn: in.OrderSn,
		Amount:  in.Amount,
	}, nil
}
